package kuwo

import (
	"api-go/cache"
	"api-go/serializer"
	"api-go/util"
	"fmt"
	"net/url"
	"strconv"
	"strings"
	"time"

	"github.com/go-redis/redis/v8"
)

// 歌曲所需信息
type Song struct {
	Ids string `form:"id"`
	Br  string `form:"br"` //1.mp3 128k 2.320k 3.flag/ape
}

//获取歌曲链接
func (service *Song) SongUrl() *serializer.Response {

	if val := service.Ids; val != "" {
		service.Ids = val
	} else {
		service.Ids = "156483846"
	}

	if val := service.Br; val != "" {
		service.Br = val
	} else {
		service.Br = "1"
	}

	if service.Br == "1" {
		service.Br = "128kmp3"
	} else if service.Br == "2" {
		service.Br = "320kmp3"
	} else {
		service.Br = "1000kape"
	}

	url := "https://antiserver.kuwo.cn/anti.s?type=convert_url3&format=mp3&response=url&rid=" + service.Ids + "&br=" + service.Br

	res, err := util.Get(url)
	if err != nil {
		return err
	}

	out := map[string]interface{}{}

	if strconv.FormatFloat(res.(map[string]interface{})["code"].(float64), 'f', -1, 64) == "200" {
		newUrl := res.(map[string]interface{})["url"].(string)
		out["url"] = newUrl
	} else {
		out["url"] = "failed"
	}

	//获取歌曲详细信息
	url = "http://m.kuwo.cn/newh5/singles/songinfoandlrc?musicId=" + service.Ids + "&httpsStatus=1"

	ress, err := util.KuwoGet(url)
	if err != nil {
		return err
	}
	if ress.(map[string]interface{})["data"] != nil {
		resss := ress.(map[string]interface{})["data"].(map[string]interface{})["songinfo"].(map[string]interface{})
		out["id"] = resss["id"]
		out["album"] = resss["album"]
		out["name"] = resss["songName"]
		out["singer"] = resss[""]
		picUrl := resss["pic"].(string)
		out["picUrl"] = strings.Replace(picUrl, "/240/", "/500/", -1)
		//获取歌词
		ressss := ress.(map[string]interface{})["data"].(map[string]interface{})["lrclist"]
		if ressss == nil {
			out["lyric"] = "[00:00:00]暂无歌词 "
		} else {
			var lyric string
			for _, v := range ressss.([]interface{}) {
				time := v.(map[string]interface{})["time"].(string)
				content := v.(map[string]interface{})["lineLyric"].(string)
				//取ms,即.后面的数字
				comma := strings.Index(time, ".")
				ms := time[comma+1:]

				newTime, _ := strconv.Atoi(time[:comma])
				m := newTime / 60

				s := newTime % 60

				//golang不支持三元表达式，所有用If判断
				var newM string
				var newS string
				if m < 10 {
					newM = "0" + strconv.Itoa(m)
				} else {
					newM = strconv.Itoa(m)
				}
				if s < 10 {
					newS = "0" + strconv.Itoa(s)
				} else {
					newS = strconv.Itoa(s)
				}
				timeString := newM + ":" + newS + ":" + ms
				lyric = lyric + "[" + timeString + "]" + content + "\n"
			}
			out["lyric"] = lyric
		}
	} else {
		out["id"] = service.Ids
		out["album"] = "获取失败"
		out["name"] = "获取失败"
		out["singer"] = "获取失败"
		out["picUrl"] = "http://qt.music.canace.cn/avatar.png"
		out["lyric"] = "获取失败"
	}

	out["platform"] = "kw"

	return serializer.OkResponse(out)
}

//获取歌曲详细信息
func (service *Song) SongInfo() *serializer.Response {

	if val := service.Ids; val != "" {
		service.Ids = val
	} else {
		service.Ids = "156483846"
	}

	url := "http://kuwo.cn/api/www/music/musicInfo?mid=" + service.Ids + "&httpsStatus=1"

	res, err := util.KuwoGet(url)
	if err != nil {
		return err
	}
	return serializer.OkResponse(res)
}

//获取歌曲歌词
func (service *Song) SongLyric() *serializer.Response {
	if val := service.Ids; val != "" {
		service.Ids = val
	} else {
		service.Ids = "156483846"
	}

	url := "http://m.kuwo.cn/newh5/singles/songinfoandlrc?musicId=" + service.Ids + "&httpsStatus=1"

	res, err := util.KuwoGet(url)
	if err != nil {
		return err
	}
	return serializer.OkResponse(res)
}

//其他接口调用酷我接口
func UsingKwSong(name, singer, br string) string {

	if a := usingKuwoSearch(name, singer); a != "failed" {

		if br == "1" {
			br = "128kmp3"
		} else if br == "2" {
			br = "320kmp3"
		} else {
			br = "1000kape"
		}

		url := "https://antiserver.kuwo.cn/anti.s?type=convert_url3&format=mp3&response=url&rid=" + a + "&br=" + br

		resss, err := util.Get(url)
		if err != nil {
			return "failed"
		}

		if strconv.FormatFloat(resss.(map[string]interface{})["code"].(float64), 'f', -1, 64) == "200" {
			newUrl := resss.(map[string]interface{})["url"].(string)
			return newUrl
		} else {
			return "failed"
		}

	} else {
		return "failed"
	}
}

//用于第三方搜索使用
func usingKuwoSearch(name, singer string) string {

	key := name + " " + singer
	//此处需要对中文进行转码，否则会无法请求第三方api
	key = url.QueryEscape(key)
	//定义redis key和判断redis是否有该值
	redisKey := "kuwo-search-" + name + "-" + singer
	redisResult, err := cache.RedisClient.Get(ctx, redisKey).Result()
	//若redis没有该值则执行获取
	if err == redis.Nil {
		url := "https://search.kuwo.cn/r.s?client=kt&all=" + key + "&pn=1&rn=1&uid=221260053&ver=kwplayer_ar_99.99.99.99&vipver=1&ft=music&cluster=0&strategy=2012&encoding=utf8&rformat=json&vermerge=1&mobi=1"

		res, err := util.KuwoGet(url)
		if err != nil {
			fmt.Println(err)
			return "failed1"
		}
		//如果有搜索结果就获取id
		var ress string
		if len(res.(map[string]interface{})["abslist"].([]interface{})) > 0 {
			ress = res.(map[string]interface{})["abslist"].([]interface{})[0].(map[string]interface{})["DC_TARGETID"].(string)
		} else {
			return "failed"
		}
		//转为string存入redis
		e := cache.RedisClient.Set(ctx, redisKey, ress, 72*time.Hour).Err()
		if e != nil {
			fmt.Println("err1", err)
			return "failed"
		}

		return ress
	} else if err != nil {
		return "failed"
	} else {
		//将从redis获取的结果（string类型）
		return redisResult
	}
}
